<template>
    <div style="border: 1px solid #ccc">
        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef"  />
        <Editor style="height: 300px; overflow-y: hidden;" @onChange="onChange" @onCreated="handleCreated" />
    </div>
</template>

<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { ref, shallowRef, onMounted, watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { UploadApi} from '@/api/index'

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

let props = defineProps({
    modelValue: {
        type: String,
        default: ''
    }
})
let emit = defineEmits(['update:modelValue'])

// 内容 HTML
const valueHtml = ref('<p>hello</p>')

// 模拟 ajax 异步获取内容
onMounted(() => {
    setTimeout(() => {
        valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>'
    }, 1500)
})

const onChange= (editor: any) => {
    console.log('内容变化', editor.getHtml())
    console.log("content",editor.children);
    emit('update:modelValue', editor.getHtml())
}

const handleCreated = (editor: any) => {
    editorRef.value = editor // 记录 editor 实例，重要！
    editor.getConfig().MENU_CONF['uploadImage'] = {
        // 自定义上传
        async customUpload(file: File, insertFn: any) {
          let reader = new FileReader()
            // file 即选中的文件
            reader.readAsDataURL(file)
            // 自己实现上传，并得到图片 url alt href
            reader.onload = () => {
                // let url = reader.result as string
                // // 插入图片的 alt
                // let alt = file.name
                // console.log(url, alt)
                UploadApi.upload.call({ name: file.name, base64: reader.result }).then((res: any) => { 
                    console.log(res);
                    
                    // 最后插入图片
            insertFn(res, "", "")
                })  

            }
           
        },
    }
}
watch(() => props.modelValue, (newValue: any, oldValue: any) => {
    console.log("进入监听函数-====");
    console.log("newValue==", newValue, oldValue);
    editorRef.value.setHtml(newValue)
    
})
</script>

<style scoped>

</style>